package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {


    //使用这个数据类型来将数据转成json格式
    private ObjectMapper objectMapper = new ObjectMapper();

    //用来获取数据库中的博客列表
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");//顺序不能颠倒
        BlogDao blogDao = new BlogDao();
        //从数据库中查询到博客列表，转成json格式，然后直接返回即可
        //先尝试获取req中的blogId请求参数
        String param = req.getParameter("blogId");

        if(param == null){
            //不存在参数
            List<Blog> blogs = blogDao.selectAll();
            //把blogs的对象转成json格式
            String respJson =  objectMapper.writeValueAsString(blogs);
            resp.getWriter().write(respJson);
        }else{
            //存在参数，获取博客详情
            int blogId = Integer.parseInt(param);
            Blog blog = blogDao.selectOne(blogId);
            String respJson = objectMapper.writeValueAsString(blog);
            resp.getWriter().write(respJson);

        }




    }


    //处理发布博客的请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if(session==null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前用户未登录");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前用户未登录");
            return;
        }

        req.setCharacterEncoding("utf8");
        //先从请求中取出参数（博客的标题和正文)
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if(title == null || "".equals(title) || content == null || "".equals(content)){
            //直接告诉客户端，参数不对
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("提交博客失败！缺少必要参数！");
            return;
        }
        //构造blog对象，把当前信息填进去，并插入到数据库中
        //要给blog设置的属性主要是title   content    usrId
        //postTime blogId 不需要手动执行

        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        //作者Id就是当前提交这个博客的用户的身份信息
        blog.setUserId(user.getUserId());
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);

        resp.sendRedirect("blog_list.html");


    }





}
















